package com.muqi.app.qlearn.fragments;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.easemob.EMEventListener;
import com.easemob.EMNotifierEvent;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.chat.EMConversation.EMConversationType;
import com.muqi.app.im.adapter.MyFragmentPagerAdapter;
import com.muqi.app.im.db.InviteMessgeDao;
import com.muqi.app.im.qmain.Constant;
import com.muqi.app.im.qmain.EMHelper;
import com.muqi.app.im.widget.TabChatWindow;
import com.muqi.app.project.utils.AppUtils;
import com.muqi.app.qlearn.student.BaseFragment;
import com.muqi.app.qlearn.student.MenuActivity;
import com.muqi.app.qlearn.student.R;
import com.wenhui.pedant.SweetAlert.SweetAlertDialog;
import com.wenhui.pedant.SweetAlert.SweetAlertDialog.OnSweetClickListener;

@SuppressLint("InflateParams") 
public class TabChat extends BaseFragment implements OnClickListener, EMEventListener {
	private RelativeLayout message_btn;
	private RelativeLayout contact_btn;
	private TextView message_tv;
	private TextView contact_tv;
	private ImageButton open_btn;
	private ViewPager clubPager;
	private MyFragmentPagerAdapter mAdapter;
	private List<Fragment> fragmentList = new ArrayList<Fragment>();
	private MessageFragment message = null;
	private ContactListFragment contact = null;
	private TabChatWindow addPopWindow = null;
	
	private BroadcastReceiver internalDebugReceiver;
	private BroadcastReceiver broadcastReceiver;
	private LocalBroadcastManager broadcastManager;
	private ImageView messageUnread;
	private ImageView friendsUnread;
	private InviteMessgeDao inviteMessgeDao;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View clubView = inflater.inflate(R.layout.fragment_tab_group, null);
		message_btn = (RelativeLayout)clubView.findViewById(R.id.message_btn);
		message_btn.setOnClickListener(this);
		contact_btn = (RelativeLayout)clubView.findViewById(R.id.contact_btn);
		contact_btn.setOnClickListener(this);
		message_tv = (TextView)clubView.findViewById(R.id.message_tv);
		contact_tv = (TextView)clubView.findViewById(R.id.contact_tv);
		messageUnread = (ImageView)clubView.findViewById(R.id.message_unread);
		friendsUnread = (ImageView)clubView.findViewById(R.id.friends_unread);
		open_btn = (ImageButton)clubView.findViewById(R.id.open_club_menu_btn);
		open_btn.setOnClickListener(this);
		clubPager = (ViewPager)clubView.findViewById(R.id.club_content);
		Init_ViewData();
		return clubView;
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 注册群组和联系人监听
        EMHelper.getInstance().registerGroupAndContactListener();
		registerBroadcastReceiver();
	}
	
	@Override
	public void onResume() {
		super.onResume();
		updateUnreadLabel();
		refreshFriendsUI();
		// unregister this event listener when this activity enters the background
		EMHelper sdkHelper = EMHelper.getInstance();
		sdkHelper.pushActivity(mActivity);
		// register the event listener when enter the foreground
		EMChatManager.getInstance().registerEventListener(this,
				new EMNotifierEvent.Event[] { EMNotifierEvent.Event.EventNewMessage ,
				EMNotifierEvent.Event.EventOfflineMessage, 
				EMNotifierEvent.Event.EventConversationListChanged });
	}

	@Override
	public void onStop() {
		EMChatManager.getInstance().unregisterEventListener(this);
		EMHelper sdkHelper = EMHelper.getInstance();
		sdkHelper.popActivity(mActivity);
		super.onStop();
	}
	
	private void registerBroadcastReceiver() {
        broadcastManager = LocalBroadcastManager.getInstance(getActivity());
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.ACTION_CONTACT_CHANAGED);
        intentFilter.addAction(Constant.ACTION_GROUP_CHANAGED);
        broadcastReceiver = new BroadcastReceiver() {
            
            @Override
            public void onReceive(Context context, Intent intent) {
            	 // 当前页面如果为聊天历史页面，刷新此页面
                if (message != null) {
                	message.refresh();
                }
                refreshFriendsUI();
                String action = intent.getAction();
                if(action.equals(Constant.ACTION_CONTACT_CHANAGED)){
                	getActivity().runOnUiThread(new Runnable() {
 						
 						@Override
 						public void run() {
 							EMHelper.getInstance().getUserProfileManager().asyncGetCurrentUserInfo();
 							
 							
 						}
 					});
                }
            }
        };
        broadcastManager.registerReceiver(broadcastReceiver, intentFilter);
    }
	
	private void refreshFriendsUI() {
		if (inviteMessgeDao == null) {
			inviteMessgeDao = new InviteMessgeDao(getActivity());
		}
		if (inviteMessgeDao.getUnreadMessagesCount() > 0) {
			friendsUnread.setVisibility(View.VISIBLE);
		} else {
			friendsUnread.setVisibility(View.INVISIBLE);
		}
	}
	
	private void unregisterBroadcastReceiver(){
	    broadcastManager.unregisterReceiver(broadcastReceiver);
	}

	@Override
	public void onEvent(EMNotifierEvent event) {
		switch (event.getEvent()) {
		case EventNewMessage: // 普通消息
			EMMessage message = (EMMessage) event.getData();
			// 提示新消息
			EMHelper.getInstance().getNotifier().onNewMsg(message);
			refreshUIWithMessage();
			break;
		case EventOfflineMessage: 
		    refreshUIWithMessage();
			break;
		case EventConversationListChanged:
		    refreshUIWithMessage();
		    break;
		default:
			break;
		}
	}
	
	private void refreshUIWithMessage() {
		// 刷新bottom bar消息未读数
		if (message != null) {
			message.refresh();
		}
		getActivity().runOnUiThread(new Runnable() {
			public void run() {
				// 刷新bottom bar消息未读数
				updateUnreadLabel();
			}
		});
	}
	
	/**
	 * 刷新未读消息数
	 */
	public void updateUnreadLabel() {
		int count = getUnreadMsgCountTotal();
		if (count > 0) {
			messageUnread.setVisibility(View.VISIBLE);
		} else {
			messageUnread.setVisibility(View.INVISIBLE);
		}
	}
	
	/**
	 * 获取未读消息数
	 * 
	 * @return
	 */
	public int getUnreadMsgCountTotal() {
		int unreadMsgCountTotal = 0;
		int chatroomUnreadMsgCount = 0;
		unreadMsgCountTotal = EMChatManager.getInstance().getUnreadMsgsCount();
		for(EMConversation conversation:EMChatManager.getInstance().getAllConversations().values()){
			if(conversation.getType() == EMConversationType.ChatRoom)
			chatroomUnreadMsgCount=chatroomUnreadMsgCount+conversation.getUnreadMsgCount();
		}
		return unreadMsgCountTotal-chatroomUnreadMsgCount;
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		unregisterBroadcastReceiver();
		try {
            getActivity().unregisterReceiver(internalDebugReceiver);
        } catch (Exception e) {
        	
        }
	}
	
	@SuppressWarnings("deprecation")
	private void Init_ViewData(){
		fragmentList.clear();
		if(message == null){ 
			message = new MessageFragment();
		}
		if(contact == null){
			contact = new ContactListFragment();
		}
		fragmentList.add(message);
		fragmentList.add(contact);
		if(mAdapter != null){
			mAdapter = null;
		}
		mAdapter = new MyFragmentPagerAdapter(getChildFragmentManager(), fragmentList);
		clubPager.setAdapter(mAdapter);
		clubPager.setOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int position) {
				resetTextView();
				switch (position) {
				case 0:
					contact_btn.setBackgroundResource(R.drawable.corners_right_bg);
					message_tv.setTextColor(getResources().getColor(R.color.green));
					break;
				case 1:
					message_btn.setBackgroundResource(R.drawable.corners_left_bg);
					contact_tv.setTextColor(getResources().getColor(R.color.green));
					break;
				}
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub
				
			}
		});
		clubPager.setCurrentItem(0);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.message_btn:
			clubPager.setCurrentItem(0);
			break;
		case R.id.contact_btn:
			clubPager.setCurrentItem(1);
			break;
		case R.id.open_club_menu_btn:
			if(addPopWindow == null){
				addPopWindow = new TabChatWindow(getActivity());
			}
			addPopWindow.showPopupWindow(open_btn);
			break;
		default:
			break;
		}
	}
	
	private void gotoLogin(){
		new SweetAlertDialog(getActivity(), SweetAlertDialog.WARNING_TYPE)
		.setTitleText("您还未登陆,请先去登录")
		.setCancelText("取消")
		.setConfirmText("登录")
		.showCancelButton(true)
		.setCancelClickListener(new OnSweetClickListener() {
			@Override
			public void onClick(SweetAlertDialog mDialog) {
				mDialog.dismissWithAnimation();
			}
		})
		.setConfirmClickListener(new OnSweetClickListener() {
			@Override
			public void onClick(SweetAlertDialog mDialog) {
				AppUtils.goToLogin(getActivity());
				mDialog.dismissWithAnimation();
			}
		}).show();
	}
	
	/**
	 * 重置颜色
	 */
	protected void resetTextView() {
		message_btn.setBackgroundResource(R.drawable.corners_white_5_radus);
		contact_btn.setBackgroundResource(R.drawable.corners_white_5_radus);
		message_tv.setTextColor(getResources().getColor(R.color.white));
		contact_tv.setTextColor(getResources().getColor(R.color.white));
	}

}
